<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
        运动会管理系统
      </div>
      <div class="flex-grow"></div>
      <div class="flex items-center gap-6">
        <div class="flex items-center gap-2">
          <img id="img-head" src="img/jstu1.webp">
          <span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
        </div>
        <div class="flex items-center gap-2">
          <a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
        </div>
      </div>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="menu-item" :class="{ active: $route.path === '/admin' }">
        <span class="iconify" data-icon="mdi:view-dashboard"></span>
        <a @click="$router.push('/admin')">系统管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
        <span class="iconify" data-icon="mdi:account-group"></span>
        <a @click="$router.push('/admin/users')">用户管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
        <span class="iconify" data-icon="mdi:clipboard-list"></span>
        <a @click="$router.push('/admin/projects')">项目管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
        <span class="iconify" data-icon="mdi:calendar-clock"></span>
        <a @click="$router.push('/admin/schedule')">赛程管理</a>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/referee' }">
        <span class="iconify" data-icon="mdi:whistle"></span>
        <a @click="$router.push('/admin/referee')">裁判管理</a>
      </div>
      <div class="menu-item active">
        <span class="iconify" data-icon="mdi:account-switch"></span>
        裁判分配
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="content">
      <!-- 面包屑导航 -->
      <el-breadcrumb class="breadcrumb" separator="/">
        <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/admin/referee' }">裁判管理</el-breadcrumb-item>
        <el-breadcrumb-item>裁判分配</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="main-content-header">
        <h1 class="text-2xl font-medium">裁判分配管理</h1>
        <div class="header-actions">
          <el-button type="success" size="small" @click="handleAutoAssign">
            <i class="el-icon-magic-stick"></i> 自动分配
          </el-button>
          <el-button type="info" size="small" @click="handleRecommendReferees">
            <i class="el-icon-star-on"></i> 推荐裁判
          </el-button>
          <el-button type="primary" size="small" @click="handleManualAssign">
            <i class="el-icon-plus"></i> 手动分配
          </el-button>
        </div>
      </div>

      <!-- 项目选择器 -->
      <div class="project-selector">
        <el-card shadow="hover">
          <template #header>
            <div class="project-selector-header">
              <span>项目选择</span>
              <el-button type="text" @click="refreshProjects">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </div>
          </template>
          <el-form :inline="true" size="small">
            <el-form-item label="选择项目">
              <el-select
                v-model="selectedProjectId"
                placeholder="请选择项目"
                clearable
                @change="handleProjectChange"
                style="width: 300px">
                <el-option
                  v-for="project in projectList"
                  :key="project.id"
                  :label="`${project.name} (${project.type})`"
                  :value="project.id">
                  <div class="project-option">
                    <span class="project-name">{{ project.name }}</span>
                    <el-tag size="mini" :type="getProjectTypeTag(project.type)">{{ project.type }}</el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分配状态">
              <el-select v-model="assignmentStatus" placeholder="请选择状态" clearable @change="handleStatusChange">
                <el-option label="待确认" value="PENDING"></el-option>
                <el-option label="已接受" value="ACCEPTED"></el-option>
                <el-option label="已拒绝" value="REJECTED"></el-option>
                <el-option label="已取消" value="CANCELLED"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 项目信息卡片 -->
      <div v-if="selectedProject" class="project-info-card">
        <el-card shadow="hover">
          <template #header>
            <div>
              <span>项目信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">项目名称：</span>
                <span class="info-value">{{ selectedProject.name }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">项目类型：</span>
                <el-tag size="small" :type="getProjectTypeTag(selectedProject.type)">
                  {{ selectedProject.type }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">比赛时间：</span>
                <span class="info-value">{{ formatDateTime(selectedProject.eventDate) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">比赛地点：</span>
                <span class="info-value">{{ selectedProject.location }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">所需裁判数：</span>
                <span class="info-value">{{ selectedProject.requiredReferees || 1 }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">已分配裁判：</span>
                <span class="info-value">{{ assignedRefereeCount }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 分配状态标签页 -->
      <div class="assignment-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="待确认" name="pending">
            <AssignmentTable
              :data="pendingAssignments"
              :loading="loading"
              status="PENDING"
              @accept="handleAcceptAssignment"
              @reject="handleRejectAssignment"
              @cancel="handleCancelAssignment"
              @refresh="loadAssignments"
            />
          </el-tab-pane>
          <el-tab-pane label="已接受" name="accepted">
            <AssignmentTable
              :data="acceptedAssignments"
              :loading="loading"
              status="ACCEPTED"
              @cancel="handleCancelAssignment"
              @refresh="loadAssignments"
            />
          </el-tab-pane>
          <el-tab-pane label="已拒绝" name="rejected">
            <AssignmentTable
              :data="rejectedAssignments"
              :loading="loading"
              status="REJECTED"
              @refresh="loadAssignments"
            />
          </el-tab-pane>
          <el-tab-pane label="已取消" name="cancelled">
            <AssignmentTable
              :data="cancelledAssignments"
              :loading="loading"
              status="CANCELLED"
              @refresh="loadAssignments"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 手动分配对话框 -->
      <el-dialog
        title="手动分配裁判"
        v-model="manualAssignDialogVisible"
        width="800px"
        :before-close="handleManualAssignClose">
        <el-form :model="manualAssignForm" :rules="manualAssignRules" ref="manualAssignFormRef" label-width="120px">
          <el-form-item label="选择项目" prop="projectId">
            <el-select v-model="manualAssignForm.projectId" placeholder="请选择项目" style="width: 100%">
              <el-option
                v-for="project in availableProjects"
                :key="project.id"
                :label="`${project.name} (${project.type})`"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择裁判" prop="refereeIds">
            <el-select
              v-model="manualAssignForm.refereeIds"
              multiple
              placeholder="请选择裁判"
              style="width: 100%">
              <el-option
                v-for="referee in availableReferees"
                :key="referee.id"
                :label="`${referee.realName} (${referee.levelName})`"
                :value="referee.id">
                <div class="referee-option">
                  <span class="referee-name">{{ referee.realName }}</span>
                  <div class="referee-info">
                    <el-tag size="mini" :type="getLevelTagType(referee.levelName)">{{ referee.levelName }}</el-tag>
                    <span class="referee-specialty">{{ referee.specialty }}</span>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执裁角色" prop="role">
            <el-select v-model="manualAssignForm.role" placeholder="请选择执裁角色" style="width: 100%">
              <el-option label="主裁判" value="主裁判"></el-option>
              <el-option label="副裁判" value="副裁判"></el-option>
              <el-option label="记录员" value="记录员"></el-option>
              <el-option label="计时员" value="计时员"></el-option>
              <el-option label="检录员" value="检录员"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input
              v-model="manualAssignForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息">
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleManualAssignClose">取消</el-button>
            <el-button type="primary" @click="handleManualAssignSave" :loading="saveLoading">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 自动分配对话框 -->
      <el-dialog
        title="自动分配裁判"
        v-model="autoAssignDialogVisible"
        width="600px">
        <el-form :model="autoAssignForm" label-width="120px">
          <el-form-item label="选择项目" prop="projectId">
            <el-select v-model="autoAssignForm.projectId" placeholder="请选择项目" style="width: 100%">
              <el-option
                v-for="project in availableProjects"
                :key="project.id"
                :label="`${project.name} (${project.type})`"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分配策略">
            <el-radio-group v-model="autoAssignForm.strategy">
              <el-radio label="SPECIALTY">按专长匹配</el-radio>
              <el-radio label="LEVEL">按资质等级</el-radio>
              <el-radio label="WORKLOAD">均衡工作负载</el-radio>
              <el-radio label="RANDOM">随机分配</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分配数量">
            <el-input-number
              v-model="autoAssignForm.count"
              :min="1"
              :max="10"
              placeholder="请输入分配数量">
            </el-input-number>
          </el-form-item>
          <el-form-item label="考虑时间段冲突">
            <el-switch v-model="autoAssignForm.avoidConflict"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="autoAssignDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAutoAssignSave" :loading="autoAssignLoading">开始分配</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 推荐裁判对话框 -->
      <el-dialog
        title="推荐裁判"
        v-model="recommendDialogVisible"
        width="900px">
        <div v-if="recommendations.length > 0">
          <el-alert
            title="推荐依据"
            type="info"
            :closable="false"
            style="margin-bottom: 20px">
            系统根据裁判专长、资质等级、历史执裁表现和工作负载等因素进行推荐
          </el-alert>
          <el-table :data="recommendations" border>
            <el-table-column prop="realName" label="姓名" width="100"></el-table-column>
            <el-table-column prop="levelName" label="资质等级" width="120">
              <template #default="scope">
                <el-tag :type="getLevelTagType(scope.row.levelName)" size="small">
                  {{ scope.row.levelName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="specialty" label="专长" width="150"></el-table-column>
            <el-table-column prop="matchScore" label="匹配度" width="100">
              <template #default="scope">
                <el-progress :percentage="scope.row.matchScore" :color="getMatchScoreColor(scope.row.matchScore)"></el-progress>
              </template>
            </el-table-column>
            <el-table-column prop="currentAssignments" label="当前分配" width="100"></el-table-column>
            <el-table-column prop="avgRating" label="平均评分" width="100">
              <template #default="scope">
                <el-rate v-model="scope.row.avgRating" disabled show-score></el-rate>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleAssignRecommended(scope.row)">
                  分配该项目
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="no-recommendations">
          <el-empty description="暂无推荐裁判"></el-empty>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="recommendDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 冲突提示对话框 -->
      <el-dialog
        title="分配冲突检测"
        v-model="conflictDialogVisible"
        width="600px">
        <div v-if="conflicts.length > 0">
          <el-alert
            title="发现时间冲突"
            type="warning"
            :closable="false"
            style="margin-bottom: 20px">
            以下裁判在该时间段已有其他执裁任务
          </el-alert>
          <el-table :data="conflicts" border>
            <el-table-column prop="refereeName" label="裁判姓名" width="120"></el-table-column>
            <el-table-column prop="conflictProject" label="冲突项目" width="150"></el-table-column>
            <el-table-column prop="conflictTime" label="冲突时间" width="180"></el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleRemoveFromSelection(scope.row)">
                  移除选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="no-conflicts">
          <el-alert
            title="未发现冲突"
            type="success"
            :closable="false">
            所选裁判时间均无冲突，可以正常分配
          </el-alert>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="conflictDialogVisible = false">关闭</el-button>
            <el-button v-if="conflicts.length === 0" type="primary" @click="handleConfirmAssignment">
              确认分配
            </el-button>
          </div>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script>
import {
  assignRefereeToProject,
  acceptAssignment,
  rejectAssignment,
  cancelAssignment,
  getRefereeAssignments,
  autoAssignReferees,
  recommendReferees,
  getAvailableRefereesForProject
} from '@/api/referee'
import {
  getProjectPage,
  getProjectById
} from '@/api/project'
import AssignmentTable from './components/AssignmentTable.vue'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'RefereeAssignment',
  setup() {
    const authStore = useAuthStore()
    return {
      authStore
    }
  },
  components: {
    AssignmentTable
  },
  data() {
    return {
      // 当前用户信息
      currentUser: null,

      // 项目相关
      selectedProjectId: null,
      selectedProject: null,
      projectList: [],
      availableProjects: [],
      assignmentStatus: '',

      // 分配数据
      activeTab: 'pending',
      pendingAssignments: [],
      acceptedAssignments: [],
      rejectedAssignments: [],
      cancelledAssignments: [],
      assignedRefereeCount: 0,

      // 可用裁判
      availableReferees: [],

      // 对话框状态
      manualAssignDialogVisible: false,
      autoAssignDialogVisible: false,
      recommendDialogVisible: false,
      conflictDialogVisible: false,

      // 加载状态
      loading: false,
      saveLoading: false,
      autoAssignLoading: false,

      // 手动分配表单
      manualAssignForm: {
        projectId: null,
        refereeIds: [],
        role: '',
        remarks: ''
      },
      manualAssignRules: {
        projectId: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        refereeIds: [
          { required: true, message: '请选择裁判', trigger: 'change' }
        ],
        role: [
          { required: true, message: '请选择执裁角色', trigger: 'change' }
        ]
      },

      // 自动分配表单
      autoAssignForm: {
        projectId: null,
        strategy: 'SPECIALTY',
        count: 1,
        avoidConflict: true
      },

      // 推荐数据
      recommendations: [],

      // 冲突数据
      conflicts: []
    }
  },

  created() {
    // 获取当前用户信息
    this.currentUser = this.authStore.userInfo || JSON.parse(localStorage.getItem('user'))
    // 初始化数据
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      await this.loadProjects()
      await this.loadAvailableProjects()
    },

    // 加载项目列表
    async loadProjects() {
      try {
        const response = await getProjectPage(1, 1000, {})
        if (response.code === 200) {
          this.projectList = response.data.records || []
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
      }
    },

    // 加载可用项目
    async loadAvailableProjects() {
      try {
        const response = await getProjectPage(1, 1000, { status: '进行中' })
        if (response.code === 200) {
          this.availableProjects = response.data.records || []
        }
      } catch (error) {
        console.error('加载可用项目失败:', error)
      }
    },

    // 加载分配数据
    async loadAssignments() {
      if (!this.selectedProjectId) return

      this.loading = true
      try {
        const params = {
          projectId: this.selectedProjectId
        }

        // 加载所有状态的分配
        const [pending, accepted, rejected, cancelled] = await Promise.all([
          this.loadAssignmentsByStatus('PENDING', params),
          this.loadAssignmentsByStatus('ACCEPTED', params),
          this.loadAssignmentsByStatus('REJECTED', params),
          this.loadAssignmentsByStatus('CANCELLED', params)
        ])

        this.pendingAssignments = pending
        this.acceptedAssignments = accepted
        this.rejectedAssignments = rejected
        this.cancelledAssignments = cancelled

        // 更新已分配裁判数量
        this.assignedRefereeCount = accepted.length

      } catch (error) {
        console.error('加载分配数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 按状态加载分配数据
    async loadAssignmentsByStatus(status, params) {
      try {
        const response = await getRefereeAssignments(null, { ...params, status })
        if (response.code === 200) {
          return response.data.records || []
        }
        return []
      } catch (error) {
        console.error(`加载${status}状态分配失败:`, error)
        return []
      }
    },

    // 项目改变
    async handleProjectChange(projectId) {
      if (!projectId) {
        this.selectedProject = null
        this.pendingAssignments = []
        this.acceptedAssignments = []
        this.rejectedAssignments = []
        this.cancelledAssignments = []
        this.assignedRefereeCount = 0
        return
      }

      try {
        const response = await getProjectById(projectId)
        if (response.code === 200) {
          this.selectedProject = response.data
          await this.loadAssignments()
        }
      } catch (error) {
        console.error('获取项目详情失败:', error)
      }
    },

    // 状态改变
    handleStatusChange() {
      this.loadAssignments()
    },

    // 标签页切换
    handleTabClick() {
      // 切换标签页时刷新对应数据
      this.loadAssignments()
    },

    // 刷新项目
    async refreshProjects() {
      await this.loadProjects()
      await this.loadAvailableProjects()
      if (this.selectedProjectId) {
        await this.handleProjectChange(this.selectedProjectId)
      }
    },

    // 手动分配
    async handleManualAssign() {
      if (!this.selectedProjectId) {
        this.$message.warning('请先选择项目')
        return
      }

      this.manualAssignForm.projectId = this.selectedProjectId
      await this.loadAvailableReferees(this.selectedProjectId)
      this.manualAssignDialogVisible = true
    },

    // 加载可用裁判
    async loadAvailableReferees(projectId) {
      try {
        const response = await getAvailableRefereesForProject(projectId, {})
        if (response.code === 200) {
          this.availableReferees = response.data || []
        }
      } catch (error) {
        console.error('加载可用裁判失败:', error)
      }
    },

    // 自动分配
    handleAutoAssign() {
      if (!this.selectedProjectId) {
        this.$message.warning('请先选择项目')
        return
      }

      this.autoAssignForm.projectId = this.selectedProjectId
      this.autoAssignDialogVisible = true
    },

    // 推荐裁判
    async handleRecommendReferees() {
      if (!this.selectedProjectId) {
        this.$message.warning('请先选择项目')
        return
      }

      try {
        const response = await recommendReferees(this.selectedProjectId, {})
        if (response.code === 200) {
          this.recommendations = response.data || []
          this.recommendDialogVisible = true
        }
      } catch (error) {
        console.error('获取推荐裁判失败:', error)
        this.$message.error('获取推荐裁判失败')
      }
    },

    // 保存手动分配
    handleManualAssignSave() {
      this.$refs.manualAssignFormRef.validate(async (valid) => {
        if (valid) {
          // 检查时间冲突
          await this.checkTimeConflicts()

          if (this.conflicts.length > 0) {
            this.conflictDialogVisible = true
          } else {
            await this.confirmAssignment(this.manualAssignForm)
          }
        }
      })
    },

    // 保存自动分配
    async handleAutoAssignSave() {
      this.autoAssignLoading = true
      try {
        const response = await autoAssignReferees(this.autoAssignForm.projectId, this.autoAssignForm)
        if (response.code === 200) {
          this.$message.success('自动分配成功')
          this.autoAssignDialogVisible = false
          this.loadAssignments()
        } else {
          this.$message.error(response.message || '自动分配失败')
        }
      } catch (error) {
        console.error('自动分配失败:', error)
        this.$message.error('自动分配失败')
      } finally {
        this.autoAssignLoading = false
      }
    },

    // 分配推荐裁判
    async handleAssignRecommended(referee) {
      const assignmentData = {
        projectId: this.selectedProjectId,
        refereeIds: [referee.id],
        role: '主裁判',
        remarks: '系统推荐分配'
      }

      await this.confirmAssignment(assignmentData)
      this.recommendDialogVisible = false
    },

    // 检查时间冲突
    async checkTimeConflicts() {
      // 这里应该调用API检查时间冲突
      // 暂时模拟冲突数据
      this.conflicts = []
      // 实际实现中需要调用后端API检查冲突
    },

    // 确认分配
    async confirmAssignment(assignmentData) {
      this.saveLoading = true
      try {
        const response = await assignRefereeToProject(assignmentData)
        if (response.code === 200) {
          this.$message.success('分配成功')
          this.manualAssignDialogVisible = false
          this.conflictDialogVisible = false
          this.loadAssignments()
          this.$refs.manualAssignFormRef.resetFields()
        } else {
          this.$message.error(response.message || '分配失败')
        }
      } catch (error) {
        console.error('分配失败:', error)
        this.$message.error('分配失败')
      } finally {
        this.saveLoading = false
      }
    },

    // 确认分配（冲突检测后）
    handleConfirmAssignment() {
      this.confirmAssignment(this.manualAssignForm)
    },

    // 接受分配
    async handleAcceptAssignment(assignmentId) {
      try {
        const response = await acceptAssignment(assignmentId)
        if (response.code === 200) {
          this.$message.success('已接受分配')
          this.loadAssignments()
        } else {
          this.$message.error(response.message || '接受分配失败')
        }
      } catch (error) {
        console.error('接受分配失败:', error)
        this.$message.error('接受分配失败')
      }
    },

    // 拒绝分配
    async handleRejectAssignment(assignmentId) {
      this.$prompt('请输入拒绝原因', '拒绝分配', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '请输入拒绝原因'
      }).then(async ({ value }) => {
        try {
          const response = await rejectAssignment(assignmentId, value)
          if (response.code === 200) {
            this.$message.success('已拒绝分配')
            this.loadAssignments()
          } else {
            this.$message.error(response.message || '拒绝分配失败')
          }
        } catch (error) {
          console.error('拒绝分配失败:', error)
          this.$message.error('拒绝分配失败')
        }
      })
    },

    // 取消分配
    async handleCancelAssignment(assignmentId) {
      this.$confirm('确定要取消该分配吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await cancelAssignment(assignmentId)
          if (response.code === 200) {
            this.$message.success('已取消分配')
            this.loadAssignments()
          } else {
            this.$message.error(response.message || '取消分配失败')
          }
        } catch (error) {
          console.error('取消分配失败:', error)
          this.$message.error('取消分配失败')
        }
      })
    },

    // 从选择中移除冲突裁判
    handleRemoveFromSelection(conflict) {
      const index = this.manualAssignForm.refereeIds.indexOf(conflict.refereeId)
      if (index > -1) {
        this.manualAssignForm.refereeIds.splice(index, 1)
      }
    },

    // 关闭手动分配对话框
    handleManualAssignClose() {
      this.manualAssignDialogVisible = false
      this.$refs.manualAssignFormRef.resetFields()
    },

    // 退出登录
    handleLogout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除用户信息
        this.authStore.logout()
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        // 跳转到登录页
        this.$router.push('/login')
      })
    },

    // 获取项目类型标签类型
    getProjectTypeTag(type) {
      const typeMap = {
        '田径': 'success',
        '球类': 'primary',
        '游泳': 'warning',
        '体操': 'danger',
        '武术': 'info'
      }
      return typeMap[type] || 'primary'
    },

    // 获取资质等级标签类型
    getLevelTagType(levelName) {
      const typeMap = {
        '国家级': 'danger',
        '省级': 'warning',
        '市级': 'primary',
        '校级': 'success',
        '实习': 'info'
      }
      return typeMap[levelName] || 'primary'
    },

    // 获取匹配度颜色
    getMatchScoreColor(score) {
      if (score >= 90) return '#67C23A'
      if (score >= 70) return '#E6A23C'
      return '#F56C6C'
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
  background-color: #f0f2f5;
  color: #1a1a1a;
  margin: 0;
}

/* 容器布局 */
.app-container {
  max-width: 1440px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: #2C5AA0;
  display: flex;
  align-items: center;
  padding: 0 24px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.flex-grow {
  flex-grow: 1;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-6 {
  gap: 24px;
}

.gap-2 {
  gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid #e4e7ed;
}

.menu-item {
  padding: 12px 24px;
  color: #555;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s;
  cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
  background-color: #e8eff9;
  color: #2C5AA0;
  border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
  padding: 24px;
  display: grid;
  grid-template-rows: auto auto 1fr;
  gap: 24px;
  overflow-y: auto;
}

/* 面包屑 */
.breadcrumb {
  margin-bottom: 16px;
}

.main-content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 项目选择器 */
.project-selector {
  margin-bottom: 24px;
}

.project-selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.project-name {
  flex: 1;
}

/* 项目信息卡片 */
.project-info-card {
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-value {
  color: #303133;
}

/* 分配标签页 */
.assignment-tabs {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
  padding: 24px;
  overflow: hidden;
}

/* 裁判选择器 */
.referee-option {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.referee-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.referee-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.referee-specialty {
  font-size: 12px;
  color: #909399;
}

/* 推荐裁判 */
.no-recommendations {
  text-align: center;
  padding: 40px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin: 20px 0;
}

/* 冲突检测 */
.no-conflicts {
  padding: 20px;
  background-color: #f0f9ff;
  border-radius: 8px;
  border-left: 4px solid #67C23A;
}

/* 头像和退出登录 */
#img-head {
  height: 40px;
  width: 40px;
  border-radius: 50px;
}

.denglu {
  color: white;
  font-size: 15px;
  text-decoration: none;
}

.denglu:hover {
  color: #F44346;
}

.text-sm {
  font-size: 14px;
}

.text-white {
  color: white;
}

/* Element UI 样式调整 */
.el-card {
  margin-bottom: 0;
}

.el-card__header {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.el-tabs__content {
  padding: 0;
}

.el-table {
  margin-top: 0;
}

.el-table th {
  background-color: #fafafa !important;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.el-progress {
  width: 80px;
}

.el-alert {
  margin-bottom: 16px;
}

.el-empty {
  padding: 40px;
}

</style>